/**********************************************************
 * File description:ExperimentService.cpp
 * Function:创建实验服务类
 * Current Version: 1.0.0
 * Author: 夏新宇
 * Date: 2022-10-02
 *  -----
 *  Copyright by bokun Software.
 **********************************************************/
#include "ExperimentService.h"

ExperimentService::ExperimentService()
{
    conv = new Convertion();
    path = QCoreApplication::applicationDirPath();
    sqlD = new SqliteDriver();
    sqlD->setDBDir(path);
    sqlD->openDB(DBNAME);
}

ExperimentService::~ExperimentService(){
    sqlD->closeDB();
}

/*!
 * \brief 创建实验配置信息
 *
 * \param 实验配置信息结构体(不包含experiment_id,create_time,update_time)
 *
 *
 * \return int experimentId 含有实验配置信息的结构体(不包含主键、创建时间、更新时间)
 *
 * Detail here!!!
 */
QString ExperimentService::createExperiment(Experiment experiment){
    sqlD->addData(EXPERIMENT_TABLE,experiment.structToQHash());
    QList<QHash<QString,QString>> res;
    sqlD->queryExec(conv->stringToQString(LATEST_EXPERIMENT_ID),res);
    return res[0]["experiment_id"];
}


/*!
 * \brief 更新实验反应体积
 *
 * \param int experimentId 实验id
 * \param int reactionVolume 反应体积
 *
 *
 * \return
 *
 * Detail here!!!
 */
void ExperimentService::updateReactionVolume(int experimentId,QString reactionVolume){
    QHash<QString,QString> data;
    data["reaction_volume"] = reactionVolume;
    data["update_time"] = "DATETIME('now','localtime')";
    sqlD->updateData(EXPERIMENT_TABLE,data,"WHERE experiment_id = " + QString::number(experimentId));
}

void ExperimentService::update(Experiment experiment){
    experiment.update_time = "DATETIME('now','localtime')";
    sqlD->updateData(EXPERIMENT_TABLE,experiment.structToQHash(),"WHERE experiment_id = " + experiment.experiment_id);
}



/*!
 * \brief 修改指定实验启动状态
 *
 * \param int experimentId 实验Id
 *
 *
 * \return
 *
 * Detail here!!!
 */
void ExperimentService::updateStateStart(int experimentId){
    QHash<QString,QString> data;
    data["is_start"] = "1";
    data["update_time"] = "DATETIME('now','localtime')";
    sqlD->updateData(EXPERIMENT_TABLE,data,"WHERE experiment_id = " + QString::number(experimentId));
}


/*!
 * \brief 修改指定实验结束状态
 *
 * \param int experimentId 实验Id
 *
 *
 * \return
 *
 * Detail here!!!
 */
void ExperimentService::updateStateEnd(int experimentId){

    QHash<QString,QString> data;
    data["is_end"] = "1";
    data["update_time"] = "DATETIME('now','localtime')";
    sqlD->updateData(EXPERIMENT_TABLE,data,"WHERE experiment_id = " + QString::number(experimentId));
}


/*!
 * \brief 获取启动后并且运行结束的实验信息，按修改时间排序
 *
 *
 * \return
 *
 * Detail here!!!
 */
QList<QHash<QString,QString>> ExperimentService::getExperimentList(){
    QList<QHash<QString,QString>> res;
    sqlD->queryExec("SELECT * FROM experiment WHERE is_start = 1 AND is_end = 0 ORDER BY update_time DESC",res);
    return res;
}



